package cn.q3c.parse.impl.oscache;

import java.net.URL;

import org.apache.log4j.Logger;

import cn.keyvalue.ccf.common.object.DetailPage;
import cn.keyvalue.ccf.common.object.Image;
import cn.keyvalue.ccf.common.util.ObjectUtils;
import cn.q3c.parse.commons.Configuration;
import cn.q3c.parse.base.BaseProcess;
import cn.q3c.parse.dao.PageDAO;
import cn.q3c.parse.dao.object.Page;

/**
 * 什么值得买数据库处理类
 * @author wangxinning
 *
 */
public class OSchinaProcessImpl implements BaseProcess{

	private static final Logger logger = Logger.getLogger(OSchinaProcessImpl.class);
	private PageDAO dao = null;

	public boolean process(Object obj) {

		DetailPage page = (DetailPage)obj;
		if( page != null )
		{
			//抓取的page对象转换为入库的page对象
			Page dbPage = new Page();
			dbPage.setHeadtitle(page.getTitle());
			dbPage.setHeadkeywords(page.getKeywords());
			dbPage.setHeaddescription(page.getDescription());
			
			dbPage.setBodytitle(page.getBodytitle());
			dbPage.setBodycontent(page.getBody());
			
			dbPage.setPdate(page.getDatetime());
			//dbPage.setProject("oschina");
			dbPage.setUrl(page.getUrl());
			
			//图片
			if( !ObjectUtils.isEmptyList(page.getImages()) )
			{
				String images = "";				
				for( Image img:page.getImages() )
				{
					images += "#[" + img.getSrc() + "]#";//图片保存格式，#[包裹
				}
				dbPage.setBodyimages(images);
			}
			
			
			try {
				if( dao == null )
				{
					dao = new PageDAO();
					dao.setDataSource(Configuration.getInstance().getDataSource());
				}
				
				dbPage.setProject((new URL(dbPage.getUrl())).getHost());//host
				dao.addPage(dbPage);
			} catch (Exception e) {
				return false;//入库失败
			}
		}
		
		return true;
	}
}